package com.tevintao.marketingsystem.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.tevintao.marketingsystem.R;
import com.tevintao.marketingsystem.commen.RequestManager;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.shell.Shell;
import com.tevintao.marketingsystem.tool.PhoneTool;
import com.tevintao.marketingsystem.tool.SystemPathTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ActAddAccount extends AppCompatActivity implements View.OnClickListener {

    public static final String TYPE_GREE_WX = "1";
    public static final String TYPE_RANDOM_LOCATION_BUSSINESS = "2";
//    public static final String TYPE_RANDOM_LOCATION_GIF_SHOW = "3";


    private Spinner mGroupSpinner;
    private EditText mAccountEdit;
    private Button mAddAccount;

    private List<AccountGroupBean> mGroups = new ArrayList<>();

    private LayoutInflater mLayoutInflater;
    private String mDeviceName;

    private ArrayList<String> mAccountPhoneNums = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_account);
        mGroupSpinner = (Spinner) findViewById(R.id.act_add_account_group);
        if (mGroupSpinner != null) {
            mGroupSpinner.setAdapter(mGroupAdapter);
        }
        mAccountEdit = (EditText) findViewById(R.id.act_add_account_name);
        mAddAccount = (Button) findViewById(R.id.act_add_account_add);
        if (mAddAccount != null) {
            mAddAccount.setOnClickListener(this);
        }

        mLayoutInflater = getLayoutInflater();
    }


    @Override
    protected void onPostResume() {
        super.onPostResume();
        getGroupAndAreaJson();
        if (TextUtils.isEmpty(mDeviceName)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mDeviceName = SystemPathTool.getOutPutContent(ActSetDevice.device_name_file);
                    initData();
                }
            }).start();
        }
    }

    private void initData() {
        mAccountPhoneNums.clear();
        String cmd = "ls " + AccountManager.ACCOUNT_DATA_CACHE_PATH;
        Shell.ShellCommand command = Shell.runAsRoot(cmd);
        for (String str : command.output) {
            if (AccountManager.isAccountFile(str)) {
                mAccountPhoneNums.add(str);
            }
            LogManager.getInstance().logInfo(str);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mAddAccount) {
            addAccountDialog();
        }
    }


    private void addAccountDialog() {
        String phoneNum = mAccountEdit.getText().toString();
        if (TextUtils.isEmpty(phoneNum)) {
            Toast.makeText(this, "请输入帐号", Toast.LENGTH_LONG).show();
            return;
        }

        if (mAccountPhoneNums.contains(phoneNum)) {
            Toast.makeText(this, "本地帐号列表已经存在 " + phoneNum + " 请勿再次添加!!!", Toast.LENGTH_LONG).show();
            return;
        }

        long mGroupId = mGroupSpinner.getSelectedItemId();
        if (mGroupId <= 0) {
            Toast.makeText(this, "请选择帐号组", Toast.LENGTH_LONG).show();
            return;
        }


        new AlertDialog.Builder(this).setTitle("提示!")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addAccount();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).setMessage("确定添加 帐号组" + mGroupSpinner.getSelectedItem().toString()  + " 的 帐号 " + phoneNum + "吗? ").show();
    }


    private void addAccount() {
        if (TextUtils.isEmpty(mDeviceName)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mDeviceName = SystemPathTool.getOutPutContent(ActSetDevice.device_name_file);
                }
            }).start();
            Toast.makeText(this, "获取设备信息失败,请重试!", Toast.LENGTH_LONG).show();
            return;
        }
        long mGroupId = mGroupSpinner.getSelectedItemId();
        if (mGroupId <= 0) {
            Toast.makeText(this, "请选择帐号组", Toast.LENGTH_LONG).show();
            return;
        }


        final String phoneNum = mAccountEdit.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            Toast.makeText(this, "请输入帐号", Toast.LENGTH_LONG).show();
            return;
        }

        int netType = PhoneTool.getMobileTypeInt(this);
        if (netType < 0 || netType > 3) {
            Toast.makeText(this, "网络错误，请检查移动网络", Toast.LENGTH_LONG).show();
            return;
        }
        boolean bussiness = ActSetting.isBusinessVersion(this);
        String url = String.format(UrlConfig.URL_ADD_ACCOUNT, mDeviceName, phoneNum, mGroupId, netType, bussiness ? TYPE_RANDOM_LOCATION_BUSSINESS : TYPE_GREE_WX);
        JsonObjectRequest mReportJson = new JsonObjectRequest(url, new JSONObject(), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(final JSONObject jsonObject) {
                LogManager.getInstance().logInfo(jsonObject.toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        addAccountServiceSuccess(phoneNum, jsonObject);
                    }
                }).start();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(final VolleyError error) {
                LogManager.getInstance().logInfo("addAccount error " + error.toString());
                showToast("添加帐号 网络错误 " + error.toString());
            }
        });
        RequestManager.getInstance().addRequest(mReportJson);
    }

    private void addAccountServiceSuccess(String phoneNum, JSONObject jsonObject) {
        StringBuilder sb = new StringBuilder();
        String location = "";
        try {
            if (null != jsonObject) {
                if (jsonObject.has("code")) {
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        sb.append("服务器添加成功");
                    } else {
                        sb.append("服务器添加失败");
                    }
                }
                sb.append(" ----");
                if (jsonObject.has("msg")) {
                    sb.append("msg = ");
                    sb.append(jsonObject.getString("msg"));
                }
                if (jsonObject.has("location")) {
                    location = jsonObject.getJSONObject("location").toString();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sb.append(" ---- ");
        String addMsg = AccountManager.getInstance(ActAddAccount.this).switchContext(phoneNum);
        if (AccountManager.SUCCESS_TAG.equals(addMsg)) {
            sb.append("本地帐号添加成功");
            if (!TextUtils.isEmpty(location)) {
                if (AccountManager.writeLocation(location)) {
                    sb.append(" 写入位置信息成功");
                } else {
                    sb.append(" 写入位置信息失败");
                }
            }
        } else {
            sb.append("本地添加帐号失败 ").append(addMsg);
        }
        showPromptDialog(sb.toString());
    }

    private void showPromptDialog(final String message) {
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(ActAddAccount.this).setTitle("提示")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActAddAccount.this.finish();
                            }
                        }).setMessage(message).show();
            }
        });
    }

    private void showToast(final String msg) {
        mAddAccount.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ActAddAccount.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    public void getGroupAndAreaJson() {
        JsonObjectRequest mReportJson = new JsonObjectRequest(UrlConfig.URL_GET_GROUP, new JSONObject(), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(final JSONObject jsonObject) {
                LogManager.getInstance().logInfo(jsonObject.toString());
                mGroups.clear();
                try {
                    if (jsonObject != null) {
                        if (jsonObject.has("goups")) {
                            JSONArray groups = jsonObject.getJSONArray("goups");
                            for (int i = 0, len = groups.length(); i < len; i++) {
                                JSONObject json = groups.getJSONObject(i);
                                AccountGroupBean bean = new AccountGroupBean();
                                if (json.has("id")) {
                                    bean.setId(json.getInt("id"));
                                }
                                if (json.has("name")) {
                                    bean.setName(json.getString("name"));
                                }
                                mGroups.add(bean);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mAddAccount.post(new Runnable() {
                    @Override
                    public void run() {

                        mGroupAdapter.notifyDataSetChanged();
//                        Toast.makeText(ActAddAccount.this, jsonObject.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(final VolleyError error) {
                LogManager.getInstance().logInfo("getGroupAndAreaJson error " + error.toString());
                mAddAccount.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ActAddAccount.this, "网络错误 " + error.toString(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        RequestManager.getInstance().addRequest(mReportJson);
    }

    private BaseAdapter mGroupAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return mGroups.size();
        }

        @Override
        public Object getItem(int position) {
            return mGroups.get(position);
        }

        @Override
        public long getItemId(int position) {
            return mGroups.get(position).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                TextView textView = (TextView) mLayoutInflater.inflate(R.layout.add_account_spinner_item, null);
                textView.setText(((AccountGroupBean) getItem(position)).getName());
                convertView = textView;
            } else {
                TextView textView = (TextView) convertView;
                textView.setText(((AccountGroupBean) getItem(position)).getName());
            }
            return convertView;
        }
    };



    public class AccountGroupBean {
        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }

    public class AreaBean {
        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }
}
